package com.bwie.vo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.ProdsMapper;
import com.bwie.poi.DateUtils;
import com.bwie.pojo.Prods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Time;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author :Beyond🎸🎸
 * @date : 2025-10-30 19:07:40
 * @description es定时同步
 **/
@Component
public class EsTask {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProdsMapper prodsMapper;
//    定义同步数据时间的key
    public static final String cacheKey = "prod-data-to-es";
//    @Scheduled(cron ="0 0/1 * * * ?")
    public void ProdDataToEs(){
        System.out.println("定时同步商品数据到es当中："+DateUtil.now());
//        先判断索引是否存在
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProdVo.class);
        if(!indexOps.exists()){
//            如果不存在，则创建索引
            indexOps.create();
//            创建mapping映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }
        Page<Prods> prodsPage = new Page<>(1, 999);
        String now = DateUtil.now();
//        实现首次进行全量同步,后面进行增量同步需求
        if(!redisTemplate.hasKey(cacheKey)){
//            进行全量同步
            Page<Prods> prodList = prodsMapper.joinSelectProdList(prodsPage, null, null);
//            查询需要同步的商品数据
            this.syncDataToEs(prodList.getRecords());
        }else{
//              进行增量同步
            String s = redisTemplate.opsForValue().get(cacheKey);
            Page<Prods> page = prodsMapper.joinSelectProdList(prodsPage, null, s);
            //        把商品同步到es当中
            this.syncDataToEs(page.getRecords());
        }
//将上次同步时间更新到缓存当中
        redisTemplate.opsForValue().set(cacheKey,now,30, TimeUnit.MINUTES);
        System.out.println("定时同步商品数据到es任务结束");

    }
    public void syncDataToEs(List<Prods> prodsList){
        if(prodsList!=null&&prodsList.size()>0){
            for (Prods prods : prodsList) {
                EsProdVo esProdVo = new EsProdVo();
                BeanUtil.copyProperties(prods,esProdVo);
                elasticsearchRestTemplate.save(esProdVo);
            }
        }

    }
}
